﻿namespace WasiewiczHomepage.Controllers
{
    using Microsoft.AspNet.Identity;
    using Models.Identity;
    using Repositories;
    using System.Threading.Tasks;
    using System.Web.Http;

    [RoutePrefix("api/Account")]
    public class AccountController : ApiController
    {
        private readonly AuthRepository repo;

        public AccountController()
        {
            this.repo = new AuthRepository();
        }

        // POST api/Account/Register
        [AllowAnonymous]
        [Route("Register")]
        public async Task<IHttpActionResult> Register(UserModel userModel)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var result = await this.repo.RegisterUser(userModel);

            var errorResult = GetErrorResult(result);

            return errorResult ?? this.Ok();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.repo.Dispose();
            }

            base.Dispose(disposing);
        }

        private IHttpActionResult GetErrorResult(IdentityResult result)
        {
            if (result == null)
            {
                return InternalServerError();
            }

            if (result.Succeeded)
            {
                return null;
            }

            if (result.Errors != null)
            {
                foreach (var error in result.Errors)
                {
                    this.ModelState.AddModelError("", error);
                }
            }

            if (this.ModelState.IsValid)
            {
                return this.BadRequest();
            }

            return this.BadRequest(this.ModelState);
        }
    }
}